import { defineStore } from 'pinia'
import { getMatchsByIds } from '@/api/betting'
import { Match, Selection } from '@/types'
import { getMarket, getSelection, union, getItemById, isBettingLock } from '@/utils'
// import { subscribeEvents } from '@/api/socket'
import { useAppStore } from './app'

export const useMatchStore = defineStore('match', {
	state: () => ({
		subscribeData: {} as Record<string, string[]>,
		matchData: {} as Record<string, Match>
	}),
	actions: {
		setList(list: Match[], type = 'sports') {
			const eventIds: string[] = []
			list.forEach((item: Match) => {
				const { eventId } = item
				this.matchData[eventId] = item
				eventIds.push(eventId)
			})
			this.subscribeData[type] = eventIds
			this.subscribeEvents()
		},
		async setIdList(eventIds: string[], type = 'sports') {
			try {
				const { data } = await getMatchsByIds(eventIds.toString())
				data.list.forEach((item: Match) => {
					const { eventId } = item
					this.matchData[eventId] = item
				})
			} catch (error) {
			} finally {
				this.subscribeData[type] = eventIds
				this.subscribeEvents()
			}
		},
		async updateMatches() {
			try {
				const eventIds = Object.keys(this.matchData)
				const { data } = await getMatchsByIds(eventIds.toString())
				data.list.forEach((item: Match) => {
					const { eventId } = item
					this.matchData[eventId] = item
				})
			} catch (error) {
			} finally {
				this.subscribeEvents()
			}
		},
		subscribeEvents() {
			let eventIds: string[] = []
			Object.values(this.subscribeData).forEach((list: string[]) => {
				eventIds = union(eventIds, list)
			})
			Object.keys(this.matchData).forEach((eventId: string) => {
				if (!eventIds.includes(eventId)) {
					delete this.matchData[eventId]
				}
			})
			// subscribeEvents(eventIds)
		},
		updateSocket(data: any) {
			const appStore = useAppStore()
			const { eventId, status, markets, scores, isLive, liveGameState, isDisabled, locale } = data
			const event: Match = this.matchData[eventId]
			if (!event) {
				return
			}
			status && (event.status = status)
			scores && (event.scores = scores)
			isLive !== undefined && (event.isLive = isLive)
			isDisabled !== undefined && (event.isDisabled = isDisabled)
			if (liveGameState) {
				const { gameTimeBFFGotAt } = liveGameState
				const oldGameTime = event.liveGameState?.gameTime
				const oldGameTimeBFFGotAt = event.liveGameState?.gameTimeBFFGotAt
				event.liveGameState = { ...event.liveGameState, ...liveGameState }
				if (oldGameTimeBFFGotAt && gameTimeBFFGotAt < oldGameTimeBFFGotAt) {
					event.liveGameState.gameTime = oldGameTime
				}
			}
			if (!markets) {
				return
			}
			markets.forEach((newMarket: any) => {
				if (newMarket.type === 'add') {
					if (appStore.lang !== (locale || 'en')) {
						return
					}
					if (event.markets && event.markets.length) {
						event.markets = event.markets.filter(({ marketId }) => newMarket.marketId !== marketId)
						event.markets.push(newMarket)
					} else {
						event.markets = [newMarket]
					}
					return
				}
				const oldMarket: any = getItemById(event.markets, newMarket.marketId, 'marketId')
				if (!oldMarket) {
					return
				}
				const isExpired =
					oldMarket.updateTimestamp &&
					newMarket.updateTimestamp &&
					+oldMarket.updateTimestamp > +newMarket.updateTimestamp
				newMarket.isDisabled !== undefined && (oldMarket.isDisabled = newMarket.isDisabled)
				newMarket.updateTimestamp !== undefined &&
					(oldMarket.updateTimestamp = newMarket.updateTimestamp && newMarket.type === 'update')
				if (newMarket.type === 'update') {
					newMarket.selections.forEach((newSelection: Selection) => {
						const oldSelection = getItemById<Selection>(oldMarket.selections, newSelection.id)
						if (!oldSelection || (isExpired && newSelection.isDisabled === undefined)) {
							return
						}
						if (newSelection.trueOdds !== oldSelection.trueOdds) {
							oldSelection.trend = newSelection.trueOdds > oldSelection.trueOdds ? 'up' : 'down'
						}
						Object.assign(oldSelection, newSelection)
					})
				} else if (newMarket.type === 'delete') {
					oldMarket.isDisabled = newMarket.isDisabled
				}
			})
		}
	},
	getters: {
		getMatchList: (state) => (ids: string[]) => ids.map((id: string) => state.matchData[id]),
		getMatch: (state) => (id: string) => state.matchData[id],
		getMarket: (state) => (eventId: string, marketId: string) =>
			getMarket(state.matchData[eventId], marketId),
		getSelection: (state) => (eventId: string, marketId: string, selectionId: string) =>
			getSelection(state.matchData[eventId], marketId, selectionId),
		isBettingLock: (state) => (eventId: string, marketId: string, selectionId: string) => {
			const match = state.matchData[eventId]
			const market = getMarket(match, marketId)
			const selection = getSelection(match, marketId, selectionId)
			if (!match || !market || !selection) {
				return false
			}
			return isBettingLock(match, market, selection)
		}
	},
	persist: true
})
